#!/bin/bash
###
 # @Author: didiplus
 # @Date: 2024-06-20 10:07:52
 # @LastEditTime: 2024-11-12 11:42:28
 # @LastEditors: didiplus
 # @Description: 
 # @FilePath: \pythonscript\shell\monitor_login.sh
### 

# 日志文件路径
LOG_FILE="/var/log/auth.log"



# 关键词（用于检测登录失败）
KEYWORD="pam_unix(sshd:auth): authentication failure"

# 监控日志文件，实时查找关键词
tail -Fn0 "$LOG_FILE" | while read line ; do
    echo "$line" | grep "$KEYWORD" &> /dev/null
    if [ $? = 0 ]
    then
        # 发现关键词，提取相关信息
        IP=$(echo "$line" | awk '{for(i=1;i<=NF;i++){if($i ~ /rhost=/){print $i}}}' | cut -d '=' -f 2)
        USER=$(echo "$line" | awk '{for(i=1;i<=NF;i++){if($i ~ /^user=/){print $i}}}' |cut -d '=' -f 2)
        # 查询IP的归属地信息
        location=$(curl -s ipinfo.io/$IP | jq -r '"\(.country)_\(.region)_\(.city)"')
        
        sleep 5
        ## 使用第三方消息通知插件
        date=$(date +"%Y-%m-%d_%H:%M:%S")
        echo $IP,$USER,$location,$date 
        curl -X GET "https://push.spug.cc/send/YXwm6X0prb1V?user=$USER&ip=$IP&location=$location&date=$date" &>/dev/null
    fi
done
